package render

import (
	"MetroBuilderGameJam/gameEngine/drawer"
	"MetroBuilderGameJam/gameEngine/geom"
	"MetroBuilderGameJam/gameEngine/utils"
	"MetroBuilderGameJam/world"
	"github.com/hajimehoshi/ebiten/v2"
	"math"
)

func NewTrainRenderer(d *drawer.Drawer, size geom.Size, lineWidth float64) *Train {
	return &Train{
		drawer:    d,
		offsetter: newSlotOffsetCalculator(lineWidth),
		size:      size,
		lineWidth: lineWidth,
	}
}

type Train struct {
	passengerRender *Passenger

	size      geom.Size
	drawer    *drawer.Drawer
	offsetter *slotOffsetCalculator
	lineWidth float64
}

func (t *Train) SetPassengerRender(render *Passenger) {
	t.passengerRender = render
}

func (t *Train) Draw(screen *ebiten.Image, item *world.Train) *utils.Figure {
	if item.Position == nil {
		return utils.NoFigure()
	}

	if item.CurrentBranch == nil || item.CurrentBranch.RailRoad() == nil {
		return utils.NoFigure()
	}
	clr := item.CurrentBranch.RailRoad().GetColor()
	pos := *item.Position
	if item.CurrentGoal == item.CurrentBranch.To() && item.DirectionTo == item.CurrentBranch.ToStation() ||
		item.CurrentGoal != item.CurrentBranch.From() && item.DirectionTo == item.CurrentBranch.FromStation() {
		pos = pos.AsVec2().Add(t.offsetter.getToOffset(item.CurrentBranch)).AsPoint()
	} else {
		pos = pos.AsVec2().Add(t.offsetter.getFromOffset(item.CurrentBranch)).AsPoint()
	}

	if item.RelocationPlan != nil {
		clr = drawer.ColorTransparent(clr, 0.6)
	}
	vehicle := t.drawer.FillRectangle(screen, pos, t.size, item.Rotation, clr)

	t.drawPassengers(screen, item, pos)
	return utils.NewFigure(item, vehicle)
}

func (t *Train) drawPassengers(screen *ebiten.Image, item *world.Train, pos geom.Point) {
	if t.passengerRender == nil {
		return
	}

	offset := t.size.AsVec2().Mul(-1).Add(geom.NewVec2(5, 4))
	distanceW := t.size.Width * 2 / 3
	distanceH := t.size.Height

	for i, passenger := range item.Passengers() {
		p := offset.Add(geom.NewVec2(float64(i%3)*distanceW, float64(i/3)*distanceH)).Rotate(item.Rotation).Add(pos.AsVec2())
		t.passengerRender.Draw(screen, passenger, p.AsPoint(), item.Rotation+geom.Radian(math.Pi/2))
	}
}
